<?php

namespace XWAM\Addon\POrgCustomer\Model;

/**
 * CustomerFieldModel 类
 *
 * @since VER:1.0; DATE:2016-1-15; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
 */
class CustomerAttrModel extends \XWAM\Model\AppbaseModel {

    protected $tableName = 't_porg_customer_attr';

    /**
     * 保存新增属性
     * @return type
     * @since VER:1.0; DATE:2016-1-15; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
     */
    function add_attr() {
        $rules = array(
            array('field_name', 'require', '字段名称无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('field_name', 'require', '字段名称已存在!', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT),
            array('title', 'require', '属性标题无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('options_input_type', 'require', '输入类型无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('status', 'number', '状态无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->error);
        }
        if (in_array($this->options_input_type, array('select', 'radio', 'checkbox'))) {
            return $this->returnMsg(false, '配置内容无效!');
        }
        $fieldtype = '';
        switch ($this->options_input_type) {
            case 'int':
                $this->data['field_type'] = 'int';
                $fieldtype = 'int not null default 0';
                break;
            case 'decimal':
                $this->data['field_length'] = 8;
                $this->data['field_decimals'] = 2;
                $fieldtype = 'decimal(8,2) not null default 0.00';
                break;
            case 'textarea':
            case 'editor':
                $this->data['field_type'] = 'text';
                $fieldtype = 'text not null default \'\'';
                break;
            case 'datetime':
                $this->data['field_type'] = 'datetime';
                $fieldtype = 'datetime';
                break;
            case 'date':
                $this->data['field_type'] = 'char';
                $this->data['field_length'] = '10';
                $fieldtype = 'char(10) not null default \'\'';
                break;
            case 'time':
                $this->data['field_type'] = 'char';
                $this->data['field_length'] = '5';
                $fieldtype = 'char(5) not null default \'\'';
                break;
            default:
                $this->data['field_type'] = 'varchar';
                $this->data['field_length'] = '255';
                $fieldtype = 'varchar(255) not null default \'\'';
                break;
        }
        $this->is_system = 'N';
        $field_name = $this->field_name;
        $result = $this->add();
        if (false !== $result) {
            // 增加表字段 2016-1-19
            $sql='ALTER TABLE `t_porg_customer` ADD COLUMN `'.$field_name.'`  '.$fieldtype.' AFTER `create_time`;';
            $result = $this->execute($sql);
            if (!$result) {
                $this->where('id=' . $result)->delete();
            }
        }
        return $this->returnMsg($result);
    }

    /**
     * 保存编辑属性
     * @return type
     * @since VER:1.0; DATE:2016-1-20; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
     */
    function save_attr() {
        $rules = array(
            array('title', 'require', '属性标题无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('status', 'number', '类型无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->error);
        }
        $result = $this->save();
        return $this->returnMsg($result);
    }

    /**
     * 获取客户搜索字段列表
     * @since VER:1.0; DATE:2016-1-20; AUTHOR:SoChishun; DESC:Added.
     */
    function get_customer_search_list() {
        $cache_key='get_customer_search_list';
        $cache_data=S($cache_key);
        if($cache_data){
            return $cache_data;
        }
        $list = AddonD('CustomerAttr')->where("is_searchable = 'Y'")->order('sort, id')->field('field_name, title, options_input_type')->select();
        $classes = array('date', 'datetime', 'time');
        foreach ($list as &$row) {
            $input_type = $row['options_input_type'];
            $class = in_array($input_type, $classes) ? ' class="' . $input_type . 'picker"' : '';
            $row['class'] = $class;
        }
        S($cache_key,$list,15);
        return $list;
    }

    /**
     * 获取客户必填字段列表
     * @since VER:1.0; DATE:2016-1-20; AUTHOR:SoChishun; DESC:Added.
     */
    function get_customer_require_list() {
        $cache_key='get_customer_require_list';
        $cache_data=S($cache_key);
        if($cache_data){
            return $cache_data;
        }
        $list = AddonD('CustomerAttr')->where("is_required = 'Y' and is_listable = 'Y' and field_name not in ('serial_no', 'name', 'telphone', 'sex', 'address' ,'id_no', 'zip_code')")->order('sort, id')->field('field_name, title, options_input_type, options_content')->select();
        $classes = array('date', 'datetime', 'time');
        foreach ($list as &$row) {
            $input_type = $row['options_input_type'];
            $class = in_array($input_type, $classes) ? ' class="' . $input_type . 'picker"' : '';
            $row['class'] = $class;
        }
        S($cache_key,$list,15);
        return $list;
    }

    /**
     * 删除属性
     * @param type $id
     * @return type
     * @since VER:1.0; DATE:2016-1-20; AUTHOR:SoChishun; EMAIL:14507247@qq.com; DESC:Added.
     */
    function delete_attr($id = '') {
        $fields = $this->where(array('id' => array('in', $id)))->getField('field_name', true);
        $sql = '';
        foreach ($fields as $field) {
            if ($sql) {
                $sql.=',';
            }
            $sql.='DROP COLUMN `' . $field . '`';
        }
        $sql = 'ALTER TABLE `t_porg_customer` ' . $sql . ';';
        $result = $this->execute($sql);
        if (false !== $result) {
            $result = $this->delete($id);
        }
        return $this->returnMsg($result);
    }

    function change_status($id, $field, $status) {
        $result = $this->where(array('id' => $id))->setField(array($field => $status));
        return $this->returnMsg($result);
    }

    function change_sort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    // 判断字段名称是否存在 2016-1-15 SoChishun Added.
    //
    function check_attr_name($field_name) {
        return $this->where(array('field_name' => $field_name))->getField('title');
    }

    // 判断字段名称是否存在 2016-1-15 SoChishun Added.
    //
    function check_attr_title($title) {
        return $this->where(array('title' => $title))->getField('title');
    }

    // 自动建立当前租户的系统字段属性
    // 每个租户创建的时候默认都会复制一份系统客户表的属性副本到租户归属中
    // 2016-1-15 SoChishun Added.
    function generate_default_fields() {
        $n = M('t_porg_customer_attr')->count();
        if ($n > 0) {
            return;
        }
        // 
        /* 可用此语句构建
          -- 创建临时表 2016-1-15 SoChishun Added.
          create temporary table temp_customer select
          COLUMN_COMMENT as title, '基本资料' as group_name, COLUMN_NAME as field_name, DATA_TYPE as field_type, IFNULL(CHARACTER_MAXIMUM_LENGTH,'') as field_length, IFNULL(NUMERIC_SCALE,'') as field_decimals, IFNULL(COLUMN_DEFAULT,'') as field_default, COLUMN_COMMENT as help_text, LEFT(IS_NULLABLE,1) as is_required, 'Y' as is_editable, DATA_TYPE as options_input_type, COLUMN_COMMENT as options_content
          from information_schema.`COLUMNS`
          where TABLE_NAME='t_porg_customer' and TABLE_SCHEMA='db_xwam_v1' and COLUMN_NAME not in ('id','site_id','','','');

          -- 查询临时表
          select * from temp_customer;
          select concat(',(\'',title,'\', \'',group_name,'\', \'',field_name,'\', \'',field_type,'\', \'',field_length,'\', \'',field_decimals,'\', \'',field_default,'\', \'',help_text,'\', \'',is_required,'\', \'',options_input_type,'\', \'',options_content,'\')') from temp_customer;
          -- 格式化配置内容
          update temp_customer set options_content=SUBSTR(title,POSITION('(' IN title)+1) where title like '%(%';
          update temp_customer set options_content='' where options_content not like '%;%';
          update temp_customer set options_content=REPLACE(options_content,')','') where options_content <> '';
          -- 格式化标题
          update temp_customer set title=SUBSTR(title,1,POSITION('(' IN title)-1) where title like '%(%';
          update temp_customer set title=SUBSTR(title,POSITION('/' IN title)+1) where title like '%/%';
          -- 格式化帮助提示
          update temp_customer set help_text='' where field_name <> 'labels';
          update temp_customer set help_text=SUBSTR(help_text,POSITION('(' IN help_text)+1) where help_text <> '';
          update temp_customer set help_text=REPLACE(help_text,')','') where help_text <> '';
          -- 修正系统特殊属性
          update temp_customer set field_default='', options_input_type='datetime' where field_default='CURRENT_TIMESTAMP';
          update temp_customer set is_editable='N' where field_name in ('create_time', 'user_name', 'old_user_name');
          update temp_customer set options_input_type='text' where field_type in ('varchar','char');
          update temp_customer set options_input_type='int' where field_type = 'smallint';
          update temp_customer set options_input_type='select' where field_name in ('sex','id_type','vip_level','interested','contact_result');
          update temp_customer set options_input_type='textarea' where field_name in ('remark');
          update temp_customer set options_input_type='file' where field_name in ('face_url');
          -- 删除临时表
          drop table if exists temp_customer;
         */
        $sql = 'insert into t_porg_customer_attr (title, group_name, field_name, field_type, field_length, field_decimals, field_default, help_text, is_required, options_input_type, options_content) values ';
        $sql.="('客户编号', '基本资料', 'serial_no', 'varchar', '32', '', '', '', 'N', 'text', '')
,('客户姓名', '基本资料', 'name', 'varchar', '16', '', '', '', 'N', 'text', '')
,('用户头像', '基本资料', 'face_url', 'varchar', '255', '', '', '', 'Y', 'file', '')
,('性别', '基本资料', 'sex', 'varchar', '6', '', '未知', '', 'N', 'select', '女;男;未知')
,('婚姻状况', '基本资料', 'marital_status', 'varchar', '9', '', '未知', '', 'N', 'text', '')
,('生日', '基本资料', 'birthday', 'datetime', '', '', '', '', 'Y', 'datetime', '')
,('证件类型', '基本资料', 'id_type', 'varchar', '16', '', '', '', 'N', 'select', '身份证;学生证;工作证;士兵证;军官证;护照')
,('证件号码', '基本资料', 'id_no', 'varchar', '32', '', '', '', 'N', 'text', '')
,('电话号码', '基本资料', 'telphone', 'varchar', '32', '', '', '', 'N', 'text', '')
,('手机号码', '基本资料', 'mobile', 'varchar', '32', '', '', '', 'N', 'text', '')
,('联系地址', '基本资料', 'address', 'varchar', '200', '', '', '', 'N', 'text', '')
,('邮政编码', '基本资料', 'zip_code', 'varchar', '18', '', '', '', 'N', 'text', '')
,('客户等级', '基本资料', 'vip_level', 'varchar', '16', '', '', '', 'N', 'select', '普通;铜卡;银卡;金卡')
,('消费次数', '基本资料', 'buy_count', 'int', '', '0', '0', '', 'N', 'int', '')
,('累计积分', '基本资料', 'integral', 'int', '', '0', '0', '', 'N', 'int', '')
,('累计消费金额', '基本资料', 'total_amount', 'decimal', '', '2', '0.00', '', 'N', 'decimal', '')
,('最后消费时间', '基本资料', 'buy_time', 'datetime', '', '', '', '', 'Y', 'datetime', '')
,('最后联系时间', '基本资料', 'review_time', 'datetime', '', '', '', '', 'Y', 'datetime', '')
,('购买意向', '基本资料', 'interested', 'varchar', '4', '', '', '', 'N', 'select', '无;意向客户;特别兴趣')
,('联系结果', '基本资料', 'contact_result', 'varchar', '16', '', '', '', 'N', 'select', '拒绝;成功;对方为老人或小孩;接通后即结束通话;接通后不说话')
,('客户来源', '基本资料', 'source', 'varchar', '16', '', '', '', 'N', 'text', '客资导入;手动添加;来电弹屏;QQ营销')
,('工号', '基本资料', 'user_name', 'varchar', '16', '', '', '', 'N', 'text', '')
,('原工号', '基本资料', 'old_user_name', 'varchar', '16', '', '', '', 'N', 'text', '')
,('推荐人用户编号', '基本资料', 'referrer_user_id', 'int', '', '0', '0', '', 'N', 'int', '')
,('标注标签', '基本资料', 'labels', 'varchar', '32', '', '', '多个值以英文逗号隔开', 'N', 'text', '')
,('状态', '基本资料', 'status', 'smallint', '', '0', '0', '', 'N', 'int', '0:未审核;1:正常;3:冻结;4:禁用;7:注销;14:回收站')
,('备注', '基本资料', 'remark', 'varchar', '64', '', '', '', 'N', 'textarea', '')
,('创建时间', '基本资料', 'create_time', 'timestamp', '', '', '', '', 'N', 'datetime', '')";
        $this->execute($sql);
        $this->execute('update ' . $this->tableName . ' set sort=id');
        // 默认列表字段
        $this->execute('update ' . $this->tableName . ' set is_listable=\'Y\' where field_name in (\'serial_no\',\'name\',\'sex\',\'telphone\',\'address\',\'contact_result\',\'user_name\',\'labels\',\'create_time\')');
        // 默认搜索字段
        $this->execute('update ' . $this->tableName . ' set is_searchable=\'Y\' where field_name in (\'serial_no\',\'name\',\'telphone\',\'address\',\'labels\',\'create_time\')');
        // 默认导出字段
        $this->execute('update ' . $this->tableName . ' set is_exportable=\'Y\' where field_name in (\'name\',\'mobile\',\'address\')');
        // 默认导入字段
        $this->execute('update ' . $this->tableName . ' set is_importable=\'Y\' where field_name in (\'name\',\'mobile\',\'address\')');
        // 默认来电弹屏显示字段
        $this->execute('update ' . $this->tableName . ' set is_popup=\'Y\' where field_name in (\'serial_no\',\'name\',\'sex\',\'telphone\',\'address\',\'interested\',\'contact_result\',\'labels\',\'remark\')');
        // 默认必填字段
        $this->execute('update ' . $this->tableName . ' set is_required=\'Y\' where field_name in (\'serial_no\',\'name\',\'sex\',\'telphone\',\'address\',\'interested\',\'contact_result\',\'labels\',\'remark\')');
    }

}
